package com.hopes.bizz.enforcement.activemq.producer;


import com.hopes.bizz.enforcement.activemq.log.ActiveMqLogger;
import com.hopes.bizz.enforcement.activemq.config.ActiveMqStore;
import com.hopes.boss.common.core.constant.CommonConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import javax.jms.*;
import java.util.Date;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author daijie
 * @version 1.0
 * @date 2023/5/24 17:04
 * @Description:
 */
@Component
@DependsOn("activeMqStore")
@Slf4j
public class ActiveMqQueueSender {

    @Autowired
    private ActiveMqStore activeMqStore;

    @Autowired
    private ActiveMqLogger logger;

    private volatile MessageProducer producer = null;

    ReentrantLock lock = new ReentrantLock(true);

    /**
     * @see com.hopes.boss.push.PushMessages
     *  */
    public void sendUnPushMsg(String message) {
        try {
            Session session = activeMqStore.getSession();

            if (producer == null) {
                lock.lock();
                try {
                    if (producer == null) {
                        Queue queue = session.createQueue(CommonConstants.KEY_QUEUE_UNIPUSH);
                        producer = session.createProducer(queue);
                        producer.setDeliveryMode(DeliveryMode.PERSISTENT);
                        // 执行完以上方法并不能保证producer被创建好
                        Thread.sleep(1000);
                        log.info("ActiveMq uni-push生产者创建成功, queue={}", queue.getQueueName());
                    }
                } catch (JMSException e) {
                    log.error("ActiveMq uni-push生产者创建失败,错误码={},原因={}", e.getErrorCode(), e.getMessage());
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                } finally {
                    lock.unlock();
                }
            }

            // 防止多个线程之间同时使用同一个 JMS 会话
            synchronized (ActiveMqQueueSender.class) {
                TextMessage msg = session.createTextMessage(message);
                producer.send(msg);
                logger.saveTenantMqLog(true, msg.getText(), new Date(), CommonConstants.KEY_QUEUE_UNIPUSH, null,
                        producer.getDeliveryMode(), session.getAcknowledgeMode(), null, null );
            }
        } catch (JMSException e) {
            log.error("消息发送失败,错误码={},原因={}", e.getErrorCode(), e.getMessage());
            logger.saveTenantMqLog(false, message, new Date(), CommonConstants.KEY_QUEUE_UNIPUSH, null,
                    DeliveryMode.PERSISTENT, Session.AUTO_ACKNOWLEDGE, e.getErrorCode(), e.getMessage() );
        }
    }

    @PreDestroy
    private void destroy() throws JMSException {
        if (producer != null) {
            producer.close();
        }
    }
}
